# -*- coding: utf-8 -*-
# @Time : 2025/10/19 19:07:14
# @Desc : 公共方法
# @Author : Sean
# @File   : common.py
from pathlib import Path
import ctypes


def get_root_path():
    """
    @说明:获取项目根目录
    @参数:
    @参数:
    @时间:2025/10/19 19:09:08
    @作者:Sean
    @返回:pathlib.Path 对象 使用str返回str类型
    """

    return str(Path().absolute())


def get_resource_path(file_name):
    """
    @说明:获取资源文件路径 绝对路径
    @参数:file_name 文件名
    @参数:
    @时间:2025/10/19 19:09:08
    @作者:Sean
    @返回:
    """

    return str(Path(get_root_path(), file_name))


def callback_loading_html():
    """
    @说明:返回加载中页面html
    @参数:
    @参数:
    @时间:2025/10/19 19:12:42
    @作者:Sean
    @返回:
    """

    loading_html = """
        <!DOCTYPE html>
        <html lang="zh-cn">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
            <meta name="renderer" content="webkit" />
            <meta name="viewport"
                content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0" />
            <title>loading</title>
        </head>
        <body>
            <div id="app">
                <style>
                    html,
                    body,
                    #app {
                        position: relative;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 100%;
                        height: 100%;
                        overflow: hidden;
                    }
                    .load-txt {
                        position: absolute;
                        bottom: 20px;
                        left: 50%;
                        transform: translate(-50%, -50%);
                        font-size: 18px;
                        color: #333;
                    }
                    .loader,
                    .loader::before,
                    .loader::after {
                        width: 2.5em;
                        height: 2.5em;
                        border-radius: 50%;
                        animation: load-animation 1.8s infinite ease-in-out;
                        animation-fill-mode: both;
                    }

                    .loader {
                        position: relative;
                        top: 0;
                        margin: 80px auto;
                        font-size: 10px;
                        color: #333;
                        text-indent: -9999em;
                        transform: translateZ(0);
                        transform: translate(-50%, 0);
                        animation-delay: -0.16s;
                    }

                    .loader::before,
                    .loader::after {
                        position: absolute;
                        top: 0;
                        content: "";
                    }

                    .loader::before {
                        left: -3.5em;
                        animation-delay: -0.32s;
                    }

                    .loader::after {
                        left: 3.5em;
                    }

                    @keyframes load-animation {

                        0%,
                        80%,
                        100% {
                            box-shadow: 0 2.5em 0 -1.3em;
                        }

                        40% {
                            box-shadow: 0 2.5em 0 0;
                        }
                    }
                </style>
                <div class="loader"></div>
                <div class="load-txt">服务启动中</div>
            </div>
            
        </body>

        </html>
        """
    return loading_html


def callback_error_html():
    """
    @说明:返回错误页面html
    @参数:
    @参数:
    @时间:2025/10/19 19:12:42
    @作者:Sean
    @返回:
    """

    error_html = """
        <!DOCTYPE html>
        <html lang="zh-cn">
        <head>
            <meta charset="UTF-8" />
            <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
            <meta name="renderer" content="webkit" />
            <meta name="viewport"
                content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=0" />
            <title>loading</title>
            <style> 
            html,body{
                height: 100%;
                margin:0;
            }
            .error-page{
                width: 100%;
                height: 100%;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            h1{
                color:red;
            }
            </style>
        </head>
        <body>
            <div class="error-page"><h1>服务启动失败</h1></div>
        </body>
        </html>
    """
    return error_html


def get_screen_size(webview):
    """
    @说明:获取屏幕尺寸
    @参数:
    @参数:
    @时间:2025/10/21 10:13:12
    @作者:Sean
    @返回:宽  高  最小宽  最小高
    """
    screens = webview.screens
    screens = screens[0]
    width = screens.width
    height = screens.height
    # 程序窗口大小
    initWidth = int(width * 2 / 3)
    initHeight = int(height * 4 / 5)
    minWidth = int(initWidth / 2)
    minHeight = int(initHeight / 2)
    return initWidth, initHeight, minWidth, minHeight


def get_system_scale_percent() -> int:
    """
    @说明:返回 Windows 缩放显示,1 1.25 1.5 设置里那行 100/125/150/175/200...
    @参数:
    @参数:
    @时间:2025/10/27 16:55:22
    @作者:Sean
    @返回: 暂未使用该参数
    """
    PROCESS_PER_MONITOR_DPI_AWARE = 2
    try:
        # 1. 先声明 DPI 感知（Win 8.1+ 有效）
        ctypes.windll.shcore.SetProcessDpiAwareness(PROCESS_PER_MONITOR_DPI_AWARE)
    except (AttributeError, OSError):
        # 2. 老系统（Win7）退而求其次
        ctypes.windll.user32.SetProcessDPIAware()

    # 3. 现在再读
    dpi = ctypes.windll.user32.GetDpiForSystem()
    return round(dpi / 96.0, 2)


def get_free_port():
    """
    @说明:获取可用的端口 如果指定端口则直接返回
    @参数:
    @参数:
    @时间:2025/10/30 09:46:54
    @作者:Sean
    @返回:
    """

    import socket
    from contextlib import closing

    with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as s:
        try:
            s.bind(("127.0.0.1", 0))
            return s.getsockname()[1]
        except OSError:
            return -1


def check_url_is_valid(url):
    """
    @说明:检查url是否有效可访问
    @参数:url
    @参数:
    @时间:2025/10/30 09:46:54
    @作者:Sean
    @返回:True or False
    """
    import urllib.request as req

    start_num = 0
    while True:
        start_num += 1
        if start_num > 75:
            return False
        try:
            rq = req.Request(url, method="HEAD")
            resp = req.urlopen(rq, timeout=2)
            if resp.status < 400:
                return True
        except Exception:
            import time

            time.sleep(0.4)
